<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid red;
      }
    </style>
  </head>

  <body>
    <canvas id="mycanvas" width="500" height="500"></canvas>
    <script>
      // 图片加载；异步的过程；
      // 一、加载图片
      var canvas = document.querySelector("#mycanvas");
      var ctx = canvas.getContext("2d");
      // var imgurl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242332225H9-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1649819401&t=085f4d65866aa54203b7ae84daf48458"
      function loadImg(src, cb) {
        return new Promise((resolve, reject) => {
          var img = new Image();
          img.src = src;
          img.onload = function () {
            console.log("图片加载成功");
            cb && cb(img);
            resolve(img);
          };
          img.onerror = function (err) {
            console.log("图片加载失败", err);
            reject(err);
          };
        });
      }

      // 二把图片绘制再页面上；必须要等待图片加载完毕才能绘制再画布上；
      // 绘制图片
      // var imgurl = "https://gimg2.baidu.";
      var imgurl =
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242332225H9-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1649819401&t=085f4d65866aa54203b7ae84daf48458";
      // loadImg(imgurl);
      // ctx.drawImage(img, 0, 0);
      // 一、通过回调来加载图片
      // loadImg(imgurl, function (img) {
      //     ctx.drawImage(img, 0, 0);
      // })

      loadImg(imgurl).then(
        (img) => {
          console.log(img);
          ctx.drawImage(img, 0, 0);
        },
        (err) => {
          console.log(err);
        }
      );
    </script>
  </body>
</html>
